package com.yibo.yunpicture.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yibo.yunpicture.domain.space.service.SpaceUserDomainService;
import com.yibo.yunpicture.infrastructure.common.DeleteRequest;
import com.yibo.yunpicture.infrastructure.exception.BusinessException;
import com.yibo.yunpicture.infrastructure.exception.ErrorCode;
import com.yibo.yunpicture.infrastructure.exception.ThrowUtils;
import com.yibo.yunpicture.interfaces.dto.spaceuser.SpaceUserAddDTO;
import com.yibo.yunpicture.interfaces.dto.spaceuser.SpaceUserQueryDTO;
import com.yibo.yunpicture.domain.space.entity.Space;
import com.yibo.yunpicture.domain.space.entity.SpaceUser;
import com.yibo.yunpicture.domain.user.entity.User;
import com.yibo.yunpicture.domain.space.valueobject.SpaceRoleEnum;
import com.yibo.yunpicture.interfaces.vo.space.SpaceUserVO;
import com.yibo.yunpicture.interfaces.vo.space.SpaceVO;
import com.yibo.yunpicture.interfaces.vo.user.UserVO;
import com.yibo.yunpicture.application.service.SpaceApplicationService;
import com.yibo.yunpicture.application.service.SpaceUserApplicationService;
import com.yibo.yunpicture.infrastructure.mapper.SpaceUserMapper;
import com.yibo.yunpicture.application.service.UserApplicationService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author AdminMYB
* @createDate 2025-05-22 14:55:54
*/
@Service
public class SpaceUserApplicationServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
    implements SpaceUserApplicationService {
    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private SpaceApplicationService spaceApplicationService;

    @Resource
    private SpaceUserDomainService spaceUserDomainService;

    /**
     * 添加空间成员
     * @param spaceUserAddDTO
     * @return
     */
    @Override
    public long addSpaceUser(SpaceUserAddDTO spaceUserAddDTO) {
        // 参数校验
        ThrowUtils.throwIf(spaceUserAddDTO == null, ErrorCode.PARAMS_ERROR);
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserAddDTO, spaceUser);
        vaildSpaceUser(spaceUser, true);
        // 数据库操作
        boolean result = this.save(spaceUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return spaceUser.getId();
    }

    /**
     * 校验空间成员对象
     * @param spaceUser
     * @param add
     */
    @Override
    public void vaildSpaceUser(SpaceUser spaceUser, boolean add) {
        ThrowUtils.throwIf(spaceUser == null, ErrorCode.PARAMS_ERROR);
        // 创建时，空间 id 和用户 id 必填
        Long spaceId = spaceUser.getSpaceId();
        Long userId = spaceUser.getUserId();
        // 要创建
        if (add) {
            ThrowUtils.throwIf(ObjectUtil.hasEmpty(spaceId, userId), ErrorCode.PARAMS_ERROR);
            User user = userApplicationService.getUserById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR,"用户不存在");
            Space space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        }
        // 校验空间角色
        String spaceRole = spaceUser.getSpaceRole();
        SpaceRoleEnum spaceRoleEnum = SpaceRoleEnum.getEnumByValue(spaceRole);
        if( spaceRole != null && spaceRoleEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间角色不存在");
        }
    }

    /**
     * 查询请求对象
     * @param spaceUserQueryDTO
     * @return
     */
    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryDTO spaceUserQueryDTO) {
        return spaceUserDomainService.getQueryWrapper(spaceUserQueryDTO);
    }

    /**
     * 获取空间用户VO列表
     * @param spaceUserList
     * @return
     */
    @Override
    public List<SpaceUserVO> getSpaceUserVOList(List<SpaceUser> spaceUserList) {
        // 判断输入是否为空
        if (CollUtil.isEmpty(spaceUserList)) {
            return Collections.emptyList();
        }
        // 对象列表 => 封装对象列表
        List<SpaceUserVO> spaceUserVOList  = spaceUserList.stream().map(SpaceUserVO::objToVo).collect(Collectors.toList());
        // 1. 收集需要关联查询的 用户ID 和 空间ID
        Set<Long> userIdSet = spaceUserVOList.stream().map(SpaceUserVO::getUserId).collect(Collectors.toSet());
        Set<Long> spaceIdSet = spaceUserVOList.stream().map(SpaceUserVO::getSpaceId).collect(Collectors.toSet());
        // 2. 批量查询用户和空间
        Map<Long, List<User>> userIdUserListMap  = userApplicationService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        Map<Long, List<Space>> spaceIdSpaceListMap = spaceApplicationService.listByIds(spaceIdSet).stream().collect(Collectors.groupingBy(Space::getId));
        // 3. 填充 SpaceUserVO 的用户和空间信息
        spaceUserVOList.forEach(spaceUserVO -> {
            Long userId = spaceUserVO.getUserId();
            Long spaceId = spaceUserVO.getSpaceId();
            // 填充用户信息
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(user, userVO);
            spaceUserVO.setUserVO(userVO);
            // 填充空间信息
            Space space = null;
            if (spaceIdSpaceListMap.containsKey(spaceId)) {
                space = spaceIdSpaceListMap.get(spaceId).get(0);
            }
            spaceUserVO.setSpaceVO(SpaceVO.objToVo(space));
        });
        return spaceUserVOList;
    }

    /**
     * 删除空间成员
     * @param deleteRequest
     * @return
     */
    @Override
    public Boolean removeSpaceUser(DeleteRequest deleteRequest){
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0 , ErrorCode.PARAMS_ERROR,"请求参数为空");
        Long id = deleteRequest.getId();
        SpaceUser oldSpaceUser = this.getById(id);
        ThrowUtils.throwIf(oldSpaceUser == null, ErrorCode.NOT_FOUND_ERROR,"空间成员不存在");
        boolean result = this.removeById(id);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"删除失败");
        return true;
    }
}




